package net.liteheaven.xblib.widget.listview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 固定高度ListView
 *
 * 注意：item很多时谨慎使用，以防止影响效率
 *
 * Created by LiangYu on 2017/2/13
 */
public class FixedListView extends ListView {
    public FixedListView(Context context) {
        super(context);
    }

    public FixedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FixedListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(getListViewHeight(this,widthMeasureSpec,heightMeasureSpec), MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private static int getListViewHeight(ListView listView, int widthMeasureSpec, int heightMeasureSpec){
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return 0;
        }

        if (listAdapter.getCount() == 0){
            return 0;
        }

        int itemsHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
//            listItem.measure(0, 0);
            listItem.measure(widthMeasureSpec, heightMeasureSpec);
            itemsHeight += listItem.getMeasuredHeight();
        }

        int totalHeight = itemsHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        return totalHeight;
    }
}
